#!/bin/bash
#
# Master setup for keyholder

set -euxo pipefail

PACKAGES=(
  git
  libssl-dev
  python3-pip
  python3-setuptools
  python3-virtualenv
  vim
)

apt-get -y update
apt-get -y install "${PACKAGES[@]}"

# Setup keyholder-agent.service
cat > /etc/systemd/system/keyholder-agent.service<<SERVICE
[Unit]
Description=Shared keyholder SSH agent which holds shared identities

[Install]
WantedBy=multi-user.target

[Service]
User=keyholder
Group=keyholder
ExecStart=/usr/bin/ssh-agent -d -a /run/keyholder/agent.sock
ExecStop=/bin/rm -f /run/keyholder/agent.sock
SERVICE

cat > /etc/systemd/system/keyholder-proxy.service<<SERVICE
[Unit]
Description=keyholder-proxy - Filtering proxy for keyholder SSH agent
Requires=keyholder-agent.service

[Install]
WantedBy=multi-user.target

[Service]
User=keyholder
Group=keyholder
UMask=111
ExecStartPre=/bin/rm -f /run/keyholder/proxy.sock
ExecStart=/vagrant/keyholder/.venv/bin/keyholderd --bind /run/keyholder/proxy.sock --connect /run/keyholder/agent.sock
ExecStop=/bin/rm -f /run/keyholder/proxy.sock
SERVICE

/usr/sbin/groupadd -r keyholder
/usr/sbin/useradd -M -g keyholder keyholder

# Setup keyholder directories
mkdir -p /etc/keyholder.d
mkdir -p /etc/keyholder-auth.d
mkdir -p /run/keyholder

if [ ! -f /etc/keyholder-auth.d/vagrant.yml ]; then
cat > /etc/keyholder-auth.d/vagrant.yml<<AUTH
---

vagrant: [id_rsa]
AUTH
fi

if [ ! -f /etc/keyholder.d/id_rsa ]; then
	ssh-keygen -t rsa -f "/etc/keyholder.d/id_rsa" -N 'abc123'
fi

if ! grep -q '192.168.122.1' /etc/ssh/ssh_known_hosts; then
  echo 'Authorizing our own SSH host key'
  ssh-keyscan -H -t ecdsa 192.168.122.1 >> /etc/ssh/ssh_known_hosts 2> /dev/null
fi

systemctl daemon-reload
chown -R keyholder:keyholder /etc/keyholder.d
chown -R keyholder:keyholder /etc/keyholder-auth.d
chown -R keyholder:keyholder /run/keyholder
